package com.android.dumiaogou;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.dumiaogou.activity.BaseObject;
import com.android.dumiaogou.model.group.MainList;
import com.android.dumiaogou.model.group.MainListCallback;
import com.android.dumiaogou.model.group.MainSquareData;
import com.android.dumiaogou.model.group.MainSquareDataCallback;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.MyListView;
import com.android.dumiaogou.view.recycleview.CustomLoadMoreView;
import com.android.dumiaogou.adapt.MainlistAdapt;
import com.android.dumiaogou.adapt.MainlistSquareAdapt;
import com.android.dumiaogou.app.BaseActivity;
import com.android.dumiaogou.cache.search.RecordsDao;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class SearchActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.canel)
    TextView canel;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.listView)
    MyListView listView;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    @BindView(R.id.ll_search)
    ScrollView llSearch;
    @BindView(R.id.listView_result)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.ll_result)
    FrameLayout llResult;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private SearchActivity mcontext;
    private boolean networkConnected;
    private RecordsDao recordsDao;
    private SearchRecordsAdapter recordsAdapter;
    private MainlistAdapt adapter_goods;
    private String record;
    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;
    private MainlistSquareAdapt adapter_square;
    private int search_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        networkConnected = ObjectUtils.isNetworkConnected(this);
        ButterKnife.bind(this);


        mcontext = SearchActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);

        search_type = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_SEARCH_TYPE, 0);
        switch (search_type) {
            case 0:
                etSearch.setHint("搜索商品");
                initRecycleGoods();
                break;
            case 1:
                etSearch.setHint("搜索产品名看他们说");
                initRecycleSquare();
                break;

        }
        initUI();
        initSearchData();
        recordsAdapter = new SearchRecordsAdapter(this, searchRecordsList);
        listView.setAdapter(recordsAdapter);

    }

    private void initRecycleGoods() {
        adapter_goods = new MainlistAdapt(mcontext, listdatasearch_goods, "0");
        adapter_goods.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter_goods.setLoadMoreView(new CustomLoadMoreView());
        adapter_goods.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter_goods);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, listdatasearch_goods.get(position).getId(), "");
            }
        });
        adapter_goods.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        ObjectUtils.ToDetailActivity(mcontext, 1, listdatasearch_goods.get(position).getId(), "");
                        break;

                }
                return false;
            }
        });
    }

    private void initRecycleSquare() {
        adapter_square = new MainlistSquareAdapt(R.layout.item_list_square, listdatasearch_square);
        adapter_square.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter_square.setLoadMoreView(new CustomLoadMoreView());
        adapter_square.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter_square);
        adapter_square.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.item_list_square_detail:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter_square.getItem(position).getExtension_id(), "");
                        break;

                }
                return false;
            }
        });

        adapter_square.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "团详情");
                intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter_square.getItem(position).getCommon_id());
                mcontext.startActivity(intent_tuan);
            }
        });
    }

    private void initSearchData() {
        llSearch.setVisibility(View.VISIBLE);
        llResult.setVisibility(View.GONE);
        recordsDao = new RecordsDao(mcontext);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();
        tempList.addAll(recordsDao.getRecordsList());

        reversedList();
        //第一次进入判断数据库中是否有历史记录，没有则不显示
        checkRecordsSize();
    }

    private void initUI() {

        // 监听软键盘
        etSearch.setOnKeyListener(new View.OnKeyListener() {

            public boolean onKey(View v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (etSearch.getText().toString().trim().length() > 0) {

                        record = etSearch.getText().toString().trim();
                        initSearch(record);
                    } else {
                        ObjectUtils.toast(mcontext, "搜索内容不能为空");
                    }
                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                llSearch.setVisibility(View.VISIBLE);
                llResult.setVisibility(View.GONE);
                String tempName = etSearch.getText().toString().trim();
                if (tempName.length() > 0) {
                    canel.setText("搜索");


                } else {
                    canel.setText("取消");

                }
                tempList.clear();
                tempList.addAll(recordsDao.querySimlarRecord(tempName));
                reversedList();
                checkRecordsSize();
                recordsAdapter.notifyDataSetChanged();

            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(R.id.pay_name);
                record = textView.getText().toString().trim();
                etSearch.setText(record);
                initSearch(record);

            }
        });


    }

    private int page = 1;

    private void initSearch(String record) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
        }
        llSearch.setVisibility(View.GONE);
        llResult.setVisibility(View.VISIBLE);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            Refresh();
            page = 1;
            switch (search_type) {
                case 0:
                    GetListDataGoods(page, "&q=" + record);
                    break;
                case 1:
                    GetListDataSquare(page, "&goods_name=" + record);
                    break;

            }

        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
        //判断数据库中是否存在该记录
        if (!recordsDao.isHasRecord(record)) {
            tempList.add(record);
        }
        //将搜索记录保存至数据库中
        recordsDao.addRecords(record);
        reversedList();
        checkRecordsSize();
        recordsAdapter.notifyDataSetChanged();

    }

    @OnClick({R.id.canel, R.id.tv_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.canel:
                if (canel.getText().toString().equals("搜索")) {

                    record = etSearch.getText().toString().trim();
                    initSearch(record);
                } else {

                    onBackPressed();
                }
                break;
            case R.id.tv_clear:
                tempList.clear();
                reversedList();
                recordsDao.deleteAllRecords();
                recordsAdapter.notifyDataSetChanged();
                tvClear.setVisibility(View.GONE);
                tvTip.setText("无搜索记录");
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {

        page = page + 1;
        switch (search_type) {
            case 0:
                GetListDataGoods(page, "&q=" + record);
                break;
            case 1:
                GetListDataSquare(page, "&goods_name=" + record);
                break;

        }

    }

    private class SearchRecordsAdapter extends BaseAdapter {

        private List<String> searchRecordsList;
        private LayoutInflater inflater;

        public SearchRecordsAdapter(Context context, List<String> searchRecordsList) {

            this.searchRecordsList = searchRecordsList;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return searchRecordsList.size() == 0 ? 0 : searchRecordsList.size();
        }

        @Override
        public Object getItem(int position) {
            return searchRecordsList.size() == 0 ? null : searchRecordsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = inflater.inflate(R.layout.dialog_message_item, null);
                viewHolder.recordTv = (TextView) convertView.findViewById(R.id.pay_name);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            String content = searchRecordsList.get(position);
            viewHolder.recordTv.setText(content);

            return convertView;
        }

        private class ViewHolder {
            TextView recordTv;
        }
    }

    private List<String> searchRecordsList;
    private List<String> tempList;

    //当没有匹配的搜索数据的时候不显示历史记录栏
    private void checkRecordsSize() {
        if (searchRecordsList.size() == 0) {
            tvClear.setVisibility(View.GONE);
            tvTip.setText("无搜索历史");
        } else {
            tvClear.setVisibility(View.VISIBLE);
            tvTip.setText("搜索历史");
        }
    }

    //颠倒list顺序
    private void reversedList() {
        searchRecordsList.clear();
        for (int i = tempList.size() - 1; i >= 0; i--) {
            searchRecordsList.add(tempList.get(i));
        }
    }

    //获取列表数据
    private ArrayList<MainList.MainListdata.Mainlistdata> listdatasearch_goods = new ArrayList<>();
    private ArrayList<MainSquareData.DataBean.ListBean> listdatasearch_square = new ArrayList<>();

    private void GetListDataGoods(final int page, String type) {

        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?page=" + page + type;

        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            HttpUtils.get(address, null, new MainListCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    progressLoading.setVisibility(View.GONE);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainList response, int id) {
                    progressLoading.setVisibility(View.GONE);
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (page == 1) {
                        listdatasearch_goods.clear();
                        if (response.getData().getList_type() == 0) {
                            mRecyclerView.setLayoutManager(mLayoutManager);
                            mRecyclerView.setAdapter(adapter_goods);
                        } else {
                            mRecyclerView.setLayoutManager(mGridLayoutManager);
                            mRecyclerView.setAdapter(adapter_goods);
                        }

                    }
                    List<MainList.MainListdata.Mainlistdata> list = response.getData().getList();
                    if (list == null && page == 1) {
                        noData.setVisibility(View.VISIBLE);
                        return;
                    }
                    noData.setVisibility(View.GONE);
                    if (list != null) {

                        for (int i = 0; i < list.size(); i++) {
                            listdatasearch_goods.add(new MainList.MainListdata.Mainlistdata(response.getData().getList_type(), list.get(i).getId()
                                    , list.get(i).getTypeid(), list.get(i).getName(), list.get(i).getPrice(), list.get(i).getTeam_price(), list.get(i).getDiscount_price()
                                    , list.get(i).getThumb(), list.get(i).getTeam_num(), list.get(i).getTeam_people_num(), list.get(i).getLuck_num(), list.get(i).getEnd_time()
                                    , list.get(i).getStart_time(), list.get(i).getRun_time()));
                        }
                        adapter_goods.setNewData(listdatasearch_goods);
                        adapter_goods.loadMoreComplete();
                    } else if (list == null) {
                        adapter_goods.loadMoreEnd();
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络未连接");
            adapter_goods.loadMoreFail();
        }
    }

    //获取列表数据
    private void GetListDataSquare(final int page, String type) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA_SQUARE + "?page=" + page + type;
        MyLog.e("地址", address);
        if (networkConnected) {

            HttpUtils.get(address, null, new MainSquareDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainSquareData response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (page == 1) {
                        listdatasearch_square.clear();
                    }
                    if (response.getData() != null) {
                        if (response.getData().getList().size() > 0) {
                            noData.setVisibility(View.GONE);
                            listdatasearch_square.addAll(response.getData().getList());
                            adapter_square.setNewData(listdatasearch_square);
                            adapter_square.loadMoreComplete();
                        } else if (response.getData().getList().size() == 0 && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {

                            adapter_square.loadMoreEnd();
                        }

                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络未连接");
            adapter_square.loadMoreFail();

        }
    }

    private void Refresh() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    switch (search_type) {
                        case 0:
                            GetListDataGoods(page, "&q=" + record);
                            break;
                        case 1:
                            GetListDataSquare(page, "&goods_name=" + record);
                            break;

                    }
                } else {

                    ObjectUtils.toast(mcontext, "无法连接网络");
                    mRefreshLayout.setRefreshing(false);
                }


            }
        });

    }


    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        switch (search_type) {
            case 0:
                GetListDataGoods(page, "&q=" + record);
                break;
            case 1:
                GetListDataSquare(page, "&goods_name=" + record);
                break;

        }
    }


}
